﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
using System.Web;
using FreedomERP.Models;
using FreedomERP.Comm.Utils;
using System.Data.Objects;
using System.Text;
using FreedomERP.Comm;
using FreedomERP.Dao.Bd;
using FreedomERP.Dao.Bd.Impl;

namespace FreedomERP.Dao.Inv.Impl
{
    /// <summary>
    /// 送货单数据层实现类
    /// 作者：姚少鹏
    /// </summary>
    public class InvSendOrderDaoImpl : IInvSendOrderDao
    {
        FreedomERPEntities dbEntities = new FreedomERPEntities();

        /// <summary>
        /// 添加送货单
        /// </summary>
        /// <param name="sendOrder"></param>
        public void addSendOrder(InvSendOrder sendOrder)
        {
            dbEntities.InvSendOrder.AddObject(sendOrder);
            dbEntities.SaveChanges();
        }

        /// <summary>
        /// 删除送货单
        /// </summary>
        /// <author>陈新杰</author>
        /// <param name="FId"></param>
        public void delSendOrder(string FId)
        {
            InvSendOrder sendOrder = getSendOrderByFId(FId);
            if (sendOrder == null)
            {
                throw new Exception("该送货单不存在，无法删除");
            }
            string FStatusId = sendOrder.FStatusId;
            IBdCategoryDao categoryDao = new BdCategoryDaoImpl();
            BdCategory statusCate = categoryDao.getCategoryByFId(FStatusId);
            if (statusCate == null)
            {
                throw new Exception("该送货单的状态数据不存在，无法删除");
            }
            string statusNumber = statusCate.FNumber;
            if (ConstData.CATEGORY_SEND_ORDER_STATUS_DELETE.Equals(statusNumber))
            {
                throw new Exception("该送货单已经删除，无法再删除");
            }
            string deletedStutusId = categoryDao.QueryCategoryFIdByFTypeAndFNumber(ConstData.CATEGORY_SEND_ORDER_STATUS, ConstData.CATEGORY_SEND_ORDER_STATUS_DELETE);
            if (ConstData.CATEGORY_SEND_ORDER_STATUS_SAVE.Equals(statusNumber))
            {

                if (string.Empty.Equals(deletedStutusId))
                {
                    throw new Exception("'已删除'的状态ID不存在，请联系管理员");
                }
                sendOrder.FStatusId = deletedStutusId;
            }
            if (ConstData.CATEGORY_SEND_ORDER_STATUS_APPROVE.Equals(statusNumber))
            {
                List<InvShortageOrder> shortageOrders = (from shortageOrd in dbEntities.InvShortageOrder where shortageOrd.FSendOrderID == sendOrder.FId select shortageOrd).ToList();
                if (shortageOrders.Count > 0)
                {
                    string ShortageOrderUnValidStatusId = categoryDao.QueryCategoryFIdByFTypeAndFNumber(ConstData.CATEGORY_INV_SHORTAGE_STATUS_TYPE, ConstData.CATEGORY_INV_SHORTAGE_STATUS_INVALID);
                    if (string.Empty.Equals(ShortageOrderUnValidStatusId))
                    {
                        throw new Exception("'已核销'的欠货单状态ID不存在，请联系管理员");
                    }
                    InvShortageOrder shortageOrder = shortageOrders.First();
                    shortageOrder.FStatus = ShortageOrderUnValidStatusId;

                }
                sendOrder.FStatusId = deletedStutusId;
                foreach (InvSendOrderDetail detail in sendOrder.InvSendOrderDetail)
                {
                    BdProduct product = detail.BdProduct;
                    if (product == null)
                    {
                        throw new Exception("送货单详情的产品不存在。");
                    }
                    product.FQty += detail.FInvUpdateNumber;
                }

            }
            dbEntities.SaveChanges();
        }

        /// <summary>
        /// 更新送货单
        /// </summary>
        /// <param name="sendOrder"></param>
        public void updateSendOrder(InvSendOrder sendOrder)
        {
            List<InvSendOrder> sendOrderList = (from ba in dbEntities.InvSendOrder where ba.FId == sendOrder.FId select ba).ToList<InvSendOrder>();
            foreach (InvSendOrder obj in sendOrderList)
            {
                if (obj.FId.Equals(sendOrder.FId))
                {
                    obj.FNumber = sendOrder.FNumber;
                    obj.FName = sendOrder.FName;
                    obj.FCustomerId = sendOrder.FCustomerId;
                    obj.FBillDate = sendOrder.FBillDate;
                    obj.FModifyTime = sendOrder.FModifyTime;
                    obj.FModifierId = sendOrder.FModifierId;
                    obj.FApproveTime = sendOrder.FApproveTime;
                    obj.FApproverId = sendOrder.FApproverId;
                    obj.FRemark = sendOrder.FRemark;
                    obj.FStatusId = sendOrder.FStatusId;
                    obj.FOrgunitId = sendOrder.FOrgunitId;
                }
            }
            dbEntities.SaveChanges();
        }

        /// <summary>
        /// 根据FId获取送货单
        /// </summary>
        /// <param name="FId"></param>
        /// <returns></returns>
        public InvSendOrder getSendOrderByFId(string FId)
        {
            InvSendOrder obj = null;

            List<InvSendOrder> sendOrderList = (from ba in dbEntities.InvSendOrder where ba.FId == FId select ba).ToList<InvSendOrder>();
            if (sendOrderList != null && sendOrderList.Count > 0)
                obj = sendOrderList.First();

            return obj;
        }

        /// <summary>
        /// 获取送货单列表
        /// </summary>
        /// <returns></returns>
        public List<InvSendOrder> getSendOrderList()
        {
            List<InvSendOrder> sendOrderList = dbEntities.InvSendOrder.ToList<InvSendOrder>();

            return sendOrderList;
        }

        /// <summary>
        /// 获取送货单列表
        /// </summary>
        /// <param name="FStartTime"></param>
        /// <param name="FEndTime"></param>
        /// <param name="FCustomerID"></param>
        /// <param name="FOrderNumber"></param>
        /// <param name="FStatusId"></param>
        /// <param name="total"></param>
        /// <returns></returns>
       public List<InvSendOrder> getSendOrderList(string FStartTime, string FEndTime, string FCustomerID, string FOrderNumber, string FStatusId, int start, int limit, out int total, string currAccountOrgunitFId)
        {
            StringBuilder sbWhere = new StringBuilder();
            List<ObjectParameter> paramList = new List<ObjectParameter>();
            ObjectParameter param = null;

            if (FStartTime != null && !FStartTime.Equals(""))
            {
                sbWhere.Append("it.FBillDate between @FStartTime and @FEndTime and ");
                param = new ObjectParameter("FStartTime", DateUtils.ParseStringToDateTime(FStartTime));
                paramList.Add(param);
                if (FEndTime != null && !FEndTime.Equals(""))
                    param = new ObjectParameter("FEndTime", DateUtils.ParseStringToDateTime(FEndTime).AddDays(1));
                else
                    param = new ObjectParameter("FEndTime", DateUtils.GetCurDate());
                paramList.Add(param);
            }

            if (FCustomerID != null && !FCustomerID.Equals(""))
            {
                sbWhere.Append("it.FCustomerID = @FCustomerID and ");
                param = new ObjectParameter("FCustomerID", FCustomerID);
                paramList.Add(param);
            }

            if (FOrderNumber != null && !FOrderNumber.Equals(""))
            {
                sbWhere.Append("it.FNumber like @FNumber and ");
                param = new ObjectParameter("FNumber", "%" + FOrderNumber + "%");
                paramList.Add(param);
            }

            if (FStatusId != null && !FStatusId.Equals(""))
            {
                sbWhere.Append("it.FStatusId == @FStatusId and ");
                param = new ObjectParameter("FStatusId", FStatusId);
                paramList.Add(param);
            }
            else
            {
                List<BdCategory> statusCates = (from statuseCate in dbEntities.BdCategory where statuseCate.FType == ConstData.CATEGORY_SEND_ORDER_STATUS && statuseCate.FStatus == ConstData.CATEGORY_STATUS_NO select statuseCate).ToList();
                if (statusCates.Count > 0)
                {
                    /*
                    String statusId = "";
                    foreach (BdCategory status in statusCates)
                    {
                        statusId += "'"+status.FId+"'"+ ",";
                    }
                    if (statusCates.Count > 1)
                    {
                        statusId = statusId.Substring(0, statusId.Length - 1);
                    }
                     */
                    sbWhere.Append("it.FStatusId != @FStatusId and ");
                    param = new ObjectParameter("FStatusId", statusCates.First<BdCategory>().FId);
                    paramList.Add(param);

                }
            }

            sbWhere.Append("it.FOrgunitId == @FOrgunitFId and ");
            param = new ObjectParameter("FOrgunitFId", currAccountOrgunitFId);
            paramList.Add(param);

            sbWhere.Append("1=1");// 避免有多余的"and"

            ObjectParameter[] parameters = new ObjectParameter[paramList.Count];
            for (int i = 0; i < paramList.Count; i++)
            {
                parameters[i] = paramList[i];
            }
            StringBuilder sbOrder = new StringBuilder();
            sbOrder.Append("it.FModifyTime desc");
            var query = dbEntities.InvSendOrder.Where(sbWhere.ToString(), parameters).OrderBy(sbOrder.ToString());
            total = query.Count();
            List<InvSendOrder> sendOrderList = query.Skip(start).Take(limit).ToList<InvSendOrder>();

            return sendOrderList;
        }


        private string getStatusIDKeys(int count)
        {
            string result = string.Empty;
            for (int i = 0; i < count; i++)
            {
                result += ",@FStatusId_" + i;
            }
            return string.IsNullOrEmpty(result) ? string.Empty : result.Substring(1);
        }

        /// <summary>
        /// 保存修改
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        public void Save()
        {
            dbEntities.SaveChanges();
        }

        /// <summary>
        /// 审核送货单
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        public void approveSendOrder(string FId, string currAccountFId)
        {
            InvSendOrder sendOrder = getSendOrderByFId(FId);

            if (sendOrder.BdCategory != null && sendOrder.BdCategory.FNumber.Equals(ConstData.CATEGORY_SEND_ORDER_STATUS_APPROVE))
            {
                throw new Exception(ConstNoteMessage.SEND_ORDER_APPROVE_ERROR);
            }

            if (sendOrder != null)
            {
                IBdCategoryDao categoryDao = new BdCategoryDaoImpl();
                IInvShortageOrderDAO shortageOrderDAO = new InvShortageOrderDAOImpl();
                if (sendOrder.InvSendOrderDetail != null)
                {
                    List<InvShortageOrderDetail> shortageOrderDetailList = new List<InvShortageOrderDetail>();

                    foreach (InvSendOrderDetail detail in sendOrder.InvSendOrderDetail)
                    {
                        BdProduct product = detail.BdProduct;
                        product.FQty -= detail.FQty;     //扣减库存
                        detail.FInvUpdateNumber = detail.FQty;
                    }
                }
                sendOrder.FStatusId = categoryDao.QueryCategoryFIdByFTypeAndFNumber(ConstData.CATEGORY_SEND_ORDER_STATUS, ConstData.CATEGORY_SEND_ORDER_STATUS_APPROVE);
                sendOrder.FApproveTime = DateUtils.GetCurDate();
                sendOrder.FApproverId = currAccountFId;
                Save();
            }
        }

        /// <summary>
        /// 更新欠货单
        /// </summary>
        /// <param name="FId"></param>
        /// <param name="FCustomerId"></param>
        /// <param name="FRemark"></param>
        /// <param name="FStatusId"></param>
        /// <param name="FStatusNumber"></param>
        /// <param name="FUpdateAcoountId"></param>
        /// <author>陈新杰</author>
        public void updateSendOrder(string FId, string FCustomerId, string FRemark, string FStatusId, string FStatusNumber, string FUpdateAcoountId)
        {
            InvSendOrder sendOrder = getSendOrderByFId(FId);
            if (sendOrder == null)
            {
                throw new Exception("该送货单不存在，无法保存！");
            }
            if ((sendOrder.FStatusId == FStatusId) && (FStatusNumber == ConstData.CATEGORY_SEND_ORDER_STATUS_APPROVE))
            {
                throw new Exception(ConstNoteMessage.SEND_ORDER_APPROVE_ERROR);
            }
            sendOrder.FCustomerId = FCustomerId;
            sendOrder.FRemark = FRemark;
            sendOrder.FStatusId = FStatusId;
            sendOrder.FModifierId = FUpdateAcoountId;
            sendOrder.FModifyTime = DateTime.Now;
            if (FStatusNumber == ConstData.CATEGORY_SEND_ORDER_STATUS_APPROVE)
            {
                sendOrder.FApproverId = FUpdateAcoountId;
                sendOrder.FApproveTime = DateTime.Now;
                if (sendOrder != null)
                {
                    IInvShortageOrderDAO shortageOrderDAO = new InvShortageOrderDAOImpl();
                    IBdCategoryDao categoryDao = new BdCategoryDaoImpl();
                    if (sendOrder.InvSendOrderDetail != null)
                    {
                        List<InvShortageOrderDetail> shortageOrderDetailList = new List<InvShortageOrderDetail>();

                        foreach (InvSendOrderDetail detail in sendOrder.InvSendOrderDetail)
                        {
                            BdProduct product = detail.BdProduct;
                            product.FQty -= detail.FQty;     //扣减库存 
                            detail.FInvUpdateNumber = detail.FQty;
                        }
                    }
                }
            }
            dbEntities.SaveChanges();

        }

        /// <summary>
        /// 审核送货单(格力)
        /// </summary>
        /// <author>梁建东</author>
        /// <returns></returns>
        public void approveSendOrderGeLi(string FId, string currAccountFId)
        {
            InvSendOrder sendOrder = getSendOrderByFId(FId);

            if (sendOrder.BdCategory != null && sendOrder.BdCategory.FNumber.Equals(ConstData.CATEGORY_SEND_ORDER_STATUS_APPROVE))
            {
                throw new Exception(ConstNoteMessage.SEND_ORDER_APPROVE_ERROR);
            }

            if (sendOrder != null)
            {
                IBdCategoryDao categoryDao = new BdCategoryDaoImpl();
                IInvShortageOrderDAO shortageOrderDAO = new InvShortageOrderDAOImpl();
                if (sendOrder.InvSendOrderDetail != null)
                {
                    List<InvShortageOrderDetail> shortageOrderDetailList = new List<InvShortageOrderDetail>();

                    StringBuilder errorSB = new StringBuilder();
                    foreach (InvSendOrderDetail detail in sendOrder.InvSendOrderDetail)
                    {
                        BdProduct product = detail.BdProduct;
                        //检查是否缺货
                        if (detail.FQty > product.FQty)
                        {
                            //InvShortageOrderDetail shortageOrderDetail = new InvShortageOrderDetail();
                            //shortageOrderDetail.FProductId = product.FId;
                            //shortageOrderDetail.FNumber = (long)(detail.FQty - product.FQty);
                            //shortageOrderDetailList.Add(shortageOrderDetail);
                            //detail.FInvUpdateNumber = product.FQty.Value;//从库存扣除的数量
                            //product.FQty = 0;     //库存归0

                            errorSB.Append("产品[" + product.FNumber + "]的数量[" + detail.FQty + "]已超出库存数[" + product.FQty + "]<br/>");
                        }
                        else
                        {
                            product.FQty -= detail.FQty;     //扣减库存   
                            detail.FInvUpdateNumber = detail.FQty;//从库存扣除的数量
                        }
                    }
                    if (!errorSB.ToString().Equals(""))
                    {
                        throw new Exception(errorSB.ToString());
                    }
                }
                sendOrder.FStatusId = categoryDao.QueryCategoryFIdByFTypeAndFNumber(ConstData.CATEGORY_SEND_ORDER_STATUS, ConstData.CATEGORY_SEND_ORDER_STATUS_APPROVE);
                sendOrder.FApproveTime = DateUtils.GetCurDate();
                sendOrder.FApproverId = currAccountFId;
                Save();
            }
        }
    }
}
